<template>
	<view style="height:30px;">
		<uni-data-select style="width: 140px;float: right;" v-model="selected" :localdata="rType" :border="false"
			@change="change" :clear="false"></uni-data-select>
	</view>
	<view style="margin-top: 10px; margin-bottom: 10px">
		<uni-row class="demo-uni-row">
			<uni-col :span="8">
				<view class="demo-uni-col dark">
					<uni-easyinput :clearable="false" :auto-blur="false" prefixIcon="calendar" v-model="range.start"
						:placeholder="$t('start.time')" @focus="iconClick('start')"
						@iconClick="iconClick('start')" @focus.stop.prevent="handleFocus"></uni-easyinput>
				</view>
			</uni-col>
			<uni-col :span="2">
				<view class="demo-uni-col light" style="text-align: center; line-height: 30px">~</view>
			</uni-col>
			<uni-col :span="8">
				<view class="demo-uni-col light">
					<uni-easyinput :clearable="false" prefixIcon="calendar" v-model="range.end"
						:placeholder="$t('end.time')" @focus="iconClick('end')"
						@iconClick="iconClick('end')" @focus.stop.prevent="handleFocus"></uni-easyinput>
				</view>
			</uni-col>
			<uni-col :span="6">
				<view class="demo-uni-col light">
					<button type="primary" class="search" @click="search()">
						<uni-icons type="search" style="color: white"></uni-icons>
						{{ $t('aqiAnalysis.search') }}
					</button>
				</view>
			</uni-col>
		</uni-row>
	</view>
	<!-- 	<view class="charts-box">
		<uni-section title="污染物分析" type="line">
		
			<qiun-data-charts type="pie" :opts="opts1" :chartData="chartData" />
		</uni-section>
	</view> -->
	<view class="charts-box">
		<uni-section :title="$t('aqiAnalysis.polluteTrend')" type="line">
			<template v-slot:right>
				<uni-data-picker :placeholder="$t('select.pollutant')" :popup-title="$t('select.pollutant')"
					:localdata="aqiList" v-model="classes" style="width: 120px"></uni-data-picker>
			</template>
			<qiun-data-charts type="line" :opts="opts" :chartData="chartData1" :ontouch="true"/>
		</uni-section>
	</view>
	<view class="charts-box">
		<uni-section :title="$t('aqiAnalysis.polluteYOY')" type="line">
			<qiun-data-charts type="column" :opts="opts1" :chartData="chartData2" :ontouch="true"/>
		</uni-section>
	</view>
	<view>
		<uv-datetime-picker ref="datetimePicker" :cancelText="$t('system.cancel')" :confirmText="$t('system.confirm')"
			v-model="value" :mode=Ymode @confirm="confirm"></uv-datetime-picker>
	</view>
	<view>
		<!-- 提示信息弹窗 -->
		<uni-popup ref="message" type="message">
			<uni-popup-message :type="msgType" :message="messageText" :duration="2000"></uni-popup-message>
		</uni-popup>
	</view>
</template>

<script>
	import {
		getSiteId,
		formatDate,
		formatDateYear,
		getAllMonth,
		getLastMonth,
		getLastMonth_1
	} from '@/common/tools.js';

	export default {
		data() {
			const date = new Date();
			var y = date.getFullYear();
			var m = date.getMonth() + 1;
			var d = date.getDate().toString().padStart(2, '0');

			console.log(y, m, d);
			const startDate = new Date(y, m - 2, 1);
			var starty = startDate.getFullYear();
			var startm = startDate.getMonth() + 1;
			const endDate = new Date(y, m - 1, 1);
			var endy = endDate.getFullYear();
			var endm = endDate.getMonth() + 1;
			return {
				rType: [{
					value: 0,
					text: this.$t("aqiRank.day")
				}, {
					value: 1,
					text: this.$t("aqiRank.month")
				}],
				selected: 0,
				siteId: '',
				Ymode: "date", //year-month
				value: Number(new Date()),
				chartData: {},
				chartData1: {},
				chartData2: {},
				range: {
					start: starty + '-' + startm + '-' + d,
					end: endy + '-' + endm + '-' + d,
					status: ''
				},
				classes: 0,
				aqiList: [{
						text: 'aqi',
						value: 0
					},
					{
						text: 'pm25',
						value: 1
					},
					{
						text: 'pm10',
						value: 2
					},
					{
						text: 'co2',
						value: 3
					},
					{
						text: 'co',
						value: 4
					}
				],
				data: [],
				//您可以通过修改 config-ucharts.js 文件中下标为 ['column'] 的节点来配置全局默认参数，如都是默认参数，此处可以不传 opts 。实际应用过程中 opts 只需传入与全局默认参数中不一致的【某一个属性】即可实现同类型的图表显示不同的样式，达到页面简洁的需求。
				opts1: {
					color: ['#1890FF', '#91CB74', '#FAC858', '#EE6666', '#73C0DE', '#3CA272', '#FC8452', '#9A60B4',
						'#ea7ccc'
					],
					padding: [15, 15, 15, 15],
					touchMoveLimit: 24,
					enableScroll: true,
					legend: {},
					xAxis: {
						disableGrid:true,
						scrollShow:true,
						itemCount:5,
					},
					yAxis: {
						data: [{
								title:this.$t('aqiAnalysis.value'),
								position: 'left',
								min: 0
							},
							{
								
								title:this.$t('aqiAnalysis.rate'),
								position: 'right',
								min: 0
							}
						]
					},
					extra: {
						column: {
							type: 'group',
							width: 28,
							activeBgColor: '#000000',
							activeBgOpacity: 0.08,
						}
					}
				},

				opts: {
					color: ['#1890FF', '#91CB74', '#FAC858', '#EE6666', '#73C0DE', '#3CA272', '#FC8452', '#9A60B4',
						'#ea7ccc'
					],
					padding: [15, 15, 15, 15],
					enableScroll: true,
					legend:{},
					xAxis:{
						disableGrid:true,
						scrollShow:true,
						itemCount:5,
					},
					yAxis:{
						gridType: "dash",
						dashLength:2,
						data:[
							{
								position:"left",
								title:this.$t('aqiAnalysis.value'),
							},{
								position:"right",
								max:1,
								min:-1,
								title:this.$t('aqiAnalysis.rate')
							}
						]
					},
					extra: {
						line: {
							type:"curve",
							width:2,
							activeType:"hollow"
						}
					}
				}
			};
		},
		onReady() {
			this.siteId = getSiteId();
			this.change(0);
			this.getServerData();
			// this.sitename = await uni.getStorageSync("sitename");
			// console.log(this.sitename)
		},
		onNavigationBarButtonTap(event) {
			console.log('nav', event);
			this.gotoCityPage();
		},
		methods: {
			iconClick(e) {
				uni.hideKeyboard();
				this.range.status = e;
				console.log(e);
				this.$refs.datetimePicker.open();
			},
			change(e) {
				var date = new Date();
				var y = date.getFullYear();
				var m = date.getMonth() + 1;
				var d = date.getDate().toString().padStart(2, '0');
				if (e == 0) {
					this.Ymode = "date"
					this.range.end = y + "-" + m + "-" + d;
					this.range.start = y + "-" + (m - 1) + "-" + d;
				} else if (e == 1) {
					this.Ymode = "year-month"
					this.range.end = y + "-" + m;
					this.range.start = y + "-" + (m - 1);
				}

			},
			search() {
				this.getServerData();
			},
			gotoCityPage() {
				uni.navigateTo({
					url: '/pages/assist/city',
					events: {
						acceptDataFromOpenedPage: (data) => {
							this.siteId = data.id;
							// this.city = data.name;
							// this.sitename = data.phone;
							// this.monthSwitch()
							// console.log(getDate());
							// this.monthSwitch(getDate());
							this.getServerData();
						}
					}
				});
			},
			messageToggle(type, message) {
				this.msgType = type;
				this.messageText = message;
				this.$refs.message.open();
			},
			
			confirm(e) {
				this.updateValue(e.value);
			},

			updateValue(value) {
				if (this.Ymode == "year-month") {
					console.log("year-month");
					if (this.range.status == 'start') {
						this.range.start = formatDateYear(value);
					} else if (this.range.status == 'end') {
						this.range.end = formatDateYear(value);
					}
				} else if (this.Ymode == "date") {
					if (this.range.status == 'start') {
						this.range.start = formatDate(value);
					} else if (this.range.status == 'end') {
						this.range.end = formatDate(value);
					}
				}
			},

			getServerData() {
				//模拟从服务器获取数据时的延时
				if (this.Ymode == "year-month") {
					//判断月是否超过12个月
					let len = getAllMonth(this.range.start,this.range.end).length;
					if(len > 12){
						return;
					}
					let rangeDate = {
						start_date: this.range.start,
						end_date: this.range.end
					};
					this.$http.get(this.$api.aqiAnlysis.url + '/' + this.siteId, rangeDate).then((res) => {
						console.log(res);

						this.updateData(res.result);
					});
				}

				if (this.Ymode == "date") {
					//判断日是否超过30天
					let rangeDate = {
						start_date: this.range.start,
						end_date: this.range.end,
						status:1
					};
					this.$http.get(this.$api.aqiAnlysis.url + '/' + this.siteId, rangeDate).then((res) => {
						console.log(res);

						this.updateData(res.result);
					});
				}
			},

			updateYoY(data) {
				setTimeout(() => {
					//模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
					let monthList = Object.keys(data["now"]);		//获取List 遍历月份数组
					let newMonthList = monthList.slice(1);			//去掉第一个，
					let oldMonthList = Object.keys(data["last"]);
					let nData = []; //今年数据
					let lData = []; //去年数据
					newMonthList.forEach((res,index) => {
						// let reg = new RegExp('-');
						// let newRes = res.replace(reg, '');
						nData.push(data['now'][newMonthList[index]][this.aqiList[this.classes].text]);
					
					});

					oldMonthList.forEach((res,index) => {
						// let reg = new RegExp('-');
						// let newRes = res.replace(reg, '');
						lData.push(data['last'][oldMonthList[index]][this.aqiList[this.classes].text]);
					
					});
					
					let res = {
						categories: newMonthList,
						series: [{
								name: this.$t('aqiAnalysis.value'),
								data: nData
							},
							{
								name: this.$t('aqiAnalysis.rate'),
								index:1,
								data: lData
							}
						]
					};
					this.chartData2 = JSON.parse(JSON.stringify(res));
				}, 500);
			},

			updateMoM(data) {
				setTimeout(() => {
					let monthList = Object.keys(data["now"]);		//获取List 遍历月份数组
					let newMonthList = monthList.slice(1);			//去掉第一个，
		
					let nData = [];
					let nRate = [];
					newMonthList.forEach((res,index)=>{
						let currentMonthdata = data['now'][newMonthList[index]][this.aqiList[this.classes].text];
						let lastMonthdata = data['now'][monthList[index]][this.aqiList[this.classes].text]
						nData.push(currentMonthdata);
						nRate.push(((currentMonthdata-lastMonthdata)/lastMonthdata).toFixed(2));
					});
					
					let res = {
						categories: newMonthList,
						series: [{
								name: this.$t('aqiAnalysis.value'),
								data: nData
							},
							{
								name: this.$t('aqiAnalysis.rate'),
								index:1,
								data: nRate
							}
						]
					};
					this.chartData1 = JSON.parse(JSON.stringify(res));
				}, 500);
			},
			updateData(data) {
				
				
				this.updateYoY(data);
				this.updateMoM(data);
				//this.updateRate(data);
			}
		}
	};
</script>

<style scoped lang="scss">
	/* 请根据实际需求修改父元素尺寸，组件自动识别宽高 */
	uni-data-select {
		border: none !important;
	}

	.charts-box {
		width: 100%;
		height: 300px;

		/* margin: 20px; */
		qiun-data-charts {
			margin: 20px;
		}
	}

	.search {
		height: 35px;
		margin-left: 10px;
		text-align: 35px;
		font-size: 15px;
		line-height: 35px;

		uni-icons {
			color: white;
		}
	}
</style>